import render_helper from "./render_helper.mjs";
import render_content from "./render_content.mjs";
import thin_ajax from "./thin_ajax.mjs";
import datarover from "./datarover.mjs";
import { thin } from "../thin3.mjs";
import select_template from "./select_template.mjs";
import { clearafterqueue } from "./delay_render.mjs";

export default function input_template(container, template) {
  // console.log({ container, template });

  switch (template.type) {
    case "select":
      select();
      break;
    default:
      input();
      break;
  }
  function select() {
    select_template(container, { ...template, ...{ select: template.input } });
  }

  function input() {
    let input = document.createElement("input");
    container.appendChild(input);
    // console.log({ input, template });
    render_helper(input, template);
    input.name = template.input;

    if (template.ajax) {
      let uuid = thin.uuid();
      let datalist = document.createElement("datalist");
      datalist.id = uuid;
      container.appendChild(datalist);

      input.setAttribute("list", uuid);
      input.addEventListener("input", (ev) => {
        updatelist(input.value);
      });

      let ajax;
      updatelist(input.value);
      function updatelist(search) {
        if (ajax) ajax.abort(); //终止上次请求
        ajax = thin_ajax({
          url: template.ajax.url,
          data: { ...template.ajax.query, ...{ filter: { search: search } } },
          success: (data) => {
            let opt = datarover(data, template.ajax.datapath);
            thin(datalist).empty();
            // console.log({ data, opt });
            if (Array.isArray(opt)) {
              opt.forEach((op) => {
                let value = /\[\[[\w/.]+\]\]/.test(template.ajax.value)
                  ? render_content(op, template.ajax.value)
                  : datarover(op, template.ajax.value);
                let text = render_content(
                  op,
                  template.ajax.text || template.ajax.value
                );
                let option = new Option(text, value);
                datalist.appendChild(option);
              });
            }
          },
        });
      }
    }
  }
}
